<?php

namespace app\common\service;

use app\common\model\notice\EmailLog;
use PHPMailer\PHPMailer\PHPMailer;

class EmailService {

    public static function send($data)
    {
        //实例化PHPMailer核心类
        $mail = new PHPMailer();
        $mail->IsSMTP(); // 启用SMTP
        $mail->Host = env('email.host'); //SMTP服务器 以qq邮箱为例子
        $mail->Port = env('email.port');  //邮件发送端口
        $mail->SMTPAuth = true;  //启用SMTP认证
        $mail->SMTPSecure = "ssl";   // 设置安全验证方式为ssl
        $mail->CharSet = "UTF-8"; //字符集
        $mail->Encoding = "base64"; //编码方式
        $mail->Username = env('email.username');  //发件人邮箱
        $mail->Password = env('email.password');  //发件人密码 ==>重点：是授权码，不是邮箱密码
        $mail->Subject = '来自' . env('email.from_name') . '的' . $data['scene_desc']; //邮件标题
        $mail->From = env('email.from_email');  //发件人邮箱
        $mail->FromName = env('email.from_name');  //发件人姓名

        $mail->AddAddress($data['user_email']); //添加收件人
        $mail->IsHTML(true); //支持html格式内容
        $mail->Body = '尊敬的用户：<br/>您的' . $data['scene_desc'] . '如下<br/>' . '<h1>' . $data['code'] . '</h1>';//邮件主体内容
        //发送成功就删除
        if ($mail->Send()) {
            //echo "Mailer Error: ".$mail->ErrorInfo;// 输出错误信息,用以邮件发送不成功问题排查
            EmailLog::create([
                'scene_id' => $data['scene_id'],
                'email' => $data['user_email'],
                'code' => $data['code'],
                'send_status' => 1,
                'send_time' => time(),
                'create_time' => time(),
                'update_time' => time()
            ]);
            return true;
        } else {
            return false;
        }

    }

}